﻿/* **********************************************************************************
 * Copyright (c) 2011 John Hughes
 *
 * Elve Touch is licenced under the Microsoft Reciprocal License (Ms-RL).
 *
 * Project Website: http://elvetouch.codeplex.com/
 * **********************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;

namespace ElveTouch
{
    public class MemoryStreamImage : IDisposable
    {
        MemoryStream _stream;
        Image _image;

        bool _isImageValid = false;

        public MemoryStreamImage(byte[] data)
        {
            if (data != null && data.Length > 0)
            {
                try
                {
                    MemoryStream stream = new MemoryStream(data);

                    _image = Image.FromStream(stream);

                    _stream = stream;

                    _isImageValid = true;
                }
                catch
                {
                    // sometimes the file will have a bad image in it.
                }
            }
        }

        public bool IsImageValid
        {
            get { return _isImageValid; }
        }

        public Image Image
        {
            get { return _image; }
        }

        public static explicit operator Image(MemoryStreamImage msi)
        {
            if (msi._isImageValid == false)
                throw new InvalidOperationException();

            return msi.Image;
        }

        public void Dispose()
        {
            if (_image != null)
            {
                _image.Dispose();
                _image = null;
            }

            if (_stream != null)
            {
                _stream.Close();
                _stream = null;
            }

            _isImageValid = false;
        }
    }
}
